package com.helmet_back.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Command {
    public static String executeCmd(String command, String workingDirectory) throws IOException, InterruptedException {
        long start = System.currentTimeMillis(); // 记录开始时间

        // 创建进程构造器
        ProcessBuilder pb = new ProcessBuilder(command.split(" "));
        pb.directory(new java.io.File(workingDirectory)); // 设置工作目录
        pb.redirectErrorStream(true);
        // 启动进程
        Process process = pb.start();
        // 等待进程执行完毕
//        process.waitFor();
        // 使用线程异步等待进程执行
        Thread waitThread = new Thread(() -> {
            try {
                process.waitFor();
            } catch (InterruptedException e) {
                // 处理异常
            }
        });
        waitThread.start();
        // 读取进程输出
        InputStream inputStream = process.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder resultBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            resultBuilder.append(line).append("\n");
        }
        long end = System.currentTimeMillis(); // 记录结束时间
        long executionTime = end - start; // 计算执行时间
        System.out.println("springboot执行时间为：" + executionTime/1000 + " 秒");
        return resultBuilder.toString();
    }
}
